package cn.idongjia.task.client.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component("taskMapper")
public interface TaskMapper {

    @Select("select * from kp_user where uid=#{uid}")
    Map getUser(String uid);

    @Select("select * from kp_post where pid=#{pid}")
    Map getPost(String pid);

    @Insert("INSERT INTO kp_attitude (targetid, type, uid, attitude, createtm) VALUES" +
            " (#{pid}, 1, #{uid}, 1, #{tm})")
    int likePost(String pid, String uid, long tm);

    @Update("UPDATE kp_post SET likecnt=likecnt+1 WHERE pid=#{pid}")
    int incrLikeCnt(String pid);

    @Select("<script>" +
            "select r.`uid` from kp_admin_rel_user r LEFT JOIN kp_user u ON u.uid = r.uid WHERE" +
            " u.adminflag = 0 " +
            " <if test=\"exclude != null and !exclude.length != 0\"> AND uid not in " +
            "   <foreach collection=\"exclude\" index=\"index\" item=\"item\" " +
            "       open=\"(\" separator=\",\" close=\")\">" +
            "           #{item}" +
            "   </foreach>" +
            " </if>" +
            "</script>")
    List<String> getWaistcoat(@Param("exclude") String[] exclude);

    @Insert("INSERT INTO kp_statistics_user" +
            " (SELECT u.uid, sum(CASE WHEN a.attitude = 1 AND a.createtm BETWEEN #{begin} AND #{end} THEN 1 ELSE 0 END) AS likescnt," +
            "   sum(CASE WHEN r.type = 1 AND r.createtm BETWEEN #{begin} AND #{end} THEN 1 ELSE 0 END) AS replycnt," +
            "   #{ts} FROM kp_user u" +
            " LEFT JOIN kp_attitude a ON a.uid = u.uid" +
            " LEFT JOIN kp_reply r ON r.uid = u.uid GROUP BY u.uid)" +
            " ON DUPLICATE KEY UPDATE `likescnt` = likescnt, `replycnt` = replycnt")
    int addUserLikes(long begin, long end, long ts);

    @Insert("INSERT INTO kp_collect (uid, targetid, type, createtm) VALUES (#{uid},#{pid},1,#{tm})")
    int collectPost(@Param("uid") String uid, @Param("pid") String pid, @Param("tm") long tm);

    @Update("UPDATE kp_post SET collectcnt=collectcnt+1 WHERE pid=#{pid}")
    int incrCollectCnt(String pid);
}